package com.itsu.shirojwt.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.itsu.shirojwt.entity.User;
import com.itsu.shirojwt.service.UserService;
import com.itsu.shirojwt.utils.JWTUtil;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public User getUserByUserName(String username) {
        User user = jdbcTemplate.execute("select * from tb_user where user_name = '" + username +"'",
                new PreparedStatementCallback<User>() {
                    User user = null;

                    @Override
                    public User doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                        user = new User();
                        ResultSet rs = ps.executeQuery();
                        rs.next();
                        user.setUid(rs.getInt("uid"));
                        user.setUserName(rs.getString("user_name"));
                        user.setPassword(rs.getString("password"));
                        user.setStatus(rs.getInt("status"));
                        user.setRid(rs.getInt("rid"));
                        return user;
                    }
                });
        return user;
    }

    @Override
    public String generateToken(User user) {
        user = this.getUserByUserName(user.getUserName());
        return JWTUtil.sign(user.getUserName(), user.getPassword());
    }

    @Override
    public List<User> getAllUser() {
        List<User> userList = jdbcTemplate.execute(new ConnectionCallback<List<User>>() {

            @Override
            public List<User> doInConnection(Connection con) throws SQLException, DataAccessException {
                PreparedStatement ps = con.prepareStatement("select * from tb_user");
                ResultSet rs = ps.executeQuery();
                List<User> list = new ArrayList<>();
                while (rs.next()) {
                    User user = new User();
                    user.setUid(rs.getInt("uid"));
                    user.setUserName(rs.getString("user_name"));
                    user.setPassword(rs.getString("password"));
                    user.setStatus(rs.getInt("status"));
                    user.setRid(rs.getInt("rid"));
                    list.add(user);
                }
                return list;
            }
        });
        return userList;
    }

}